﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using GeoFramework;
using System.Threading;

namespace MapControl
{
    public class MapTile : IDisposable
    {
        #region vars
        private Point middle = new Point(0, 0);
        private Rectangle area = new Rectangle(0, 0, 0, 0);
        private IImageManager imgProvider;

        private readonly object locker = new object();
        private bool isLoadingImage = false;
        private Thread thLoadingImage;
        #endregion

        public event EventHandler ImageDisposing;

        public Size Size { get; private set; }
        public Point Middle
        {
            get
            {
                return middle;
            }
            set
            {
                middle = value;
                area = new Rectangle(middle.X - (Size.Width / 2), middle.Y - (Size.Height / 2), Size.Width, Size.Height);
            }
        }
        public Image TileImage { get; internal set; }
        public Position Position { get; private set; }
        public int ZoomLevel { get; private set; }
        public MapType MapType { get; private set; }
        public bool IsVisible { get; set; }
        public Rectangle VisibleAreaOfImage { get; set; }
        public Rectangle VisibleAreaOnMap { get; set; }
        public Rectangle Area
        {
            get
            {
                return area;
            }
            set
            {
                area = value;
                middle = new Point(area.X + (Size.Width / 2), middle.Y + (Size.Height / 2));
            }
        }

        public MapTile(Size size, Position position, int zoomLevel, MapType mapType, IImageManager imgManager)
        {
            this.Size = size;
            this.Position = position;
            this.ZoomLevel = zoomLevel;
            this.MapType = mapType;
            this.imgProvider = imgManager;
        }

        public void LoadImage()
        {
            if (TileImage != null)
                return;
            lock (locker)
            {
                if (isLoadingImage)
                    return;
            }
            thLoadingImage = new Thread(delegate()
            {
                imgProvider.LoadImage(this);
                lock (locker)
                {
                    isLoadingImage = false;
                }
            });
            thLoadingImage.Start();
        }

        public void DisposeImage()
        {
            if (TileImage == null)
                return;
            EventHandler h = ImageDisposing;
            if (h != null)
                h(this, EventArgs.Empty);
            TileImage.Dispose();
            TileImage = null;
        }

        #region IDisposable Members

        public void Dispose()
        {
            DisposeImage();
        }

        #endregion
    }
}
